package com.leyou.item.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.common.pojo.PageResult;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.pojo.Brand;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;

@Service
public class BrandService {

    @Autowired
    private BrandMapper brandMapper;

    public PageResult<Brand> queryBrandByPage(Integer page, Integer rows,String sortBy,Boolean desc,String key) {

        //开启分页查询
        PageHelper.startPage(page,rows);


        //拼接查询条件，（动态sql）
        Example example = new Example(Brand.class);

        //动态判断查询条件是否存在，如果存在则纳入查询语句
        if (StringUtils.isNotBlank(key)){
            Example.Criteria criteria = example.createCriteria();

            criteria.andLike("name","%"+key+"%");
        }


        //select xxx from xxx where xxxx=xxx order by id desc
        //判断排序条件不为空
        if (StringUtils.isNotBlank(sortBy)){
            example.setOrderByClause(sortBy+(desc ?" DESC" :" ASC"));//给查询条件添加order by 条件
        }


        //强转返回结果到page，会自动的统计总条目数，并且会计算总页数
        Page<Brand> select = (Page<Brand>) this.brandMapper.selectByExample(example);


        //封装分页的结果
        return new PageResult<>(select.getTotal(),new Long(select.getPages()),select);
    }


    @Transactional
    public void addBrand(Brand brand, List<Long> cids) {

        //保存brand，并回显id
        this.brandMapper.insertSelective(brand);

        cids.forEach(cid->{
            this.brandMapper.insertCategoryBrand(cid,brand.getId());
        });



    }


    @Transactional
    public void updateBrand(Brand brand, List<Long> cids) {
        //直接修改品牌
        this.brandMapper.updateByPrimaryKeySelective(brand);

        //先删除以前所有关联的分类然后再添加
        this.brandMapper.deleteCategoryByBid(brand.getId());


        cids.forEach(cid->{
            this.brandMapper.insertCategoryBrand(cid,brand.getId());
        });
    }

    public Brand queryBrandById(Long brandId) {
        return this.brandMapper.selectByPrimaryKey(brandId);
    }

    public List<Brand> queryBrandByCategory(Long cid) {
        return this.brandMapper.queryBrandByCategory(cid);
    }

}
